package com.example.itcompanyinterview.tools;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

public class AsyncImageLoader {

	public AsyncImageLoader() {
	}

	public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
		Drawable drawableImage = loadDrawableFromLocal(imageUrl);
		if(drawableImage != null) {
			return drawableImage;
		}
		
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
			}
		};
		
		new Thread() {
			@Override
			public void run() {
				String filename = CommonUrlRequest.getFileNameFromUrl(imageUrl);
				String path = "images/";
				if(CommonUrlRequest.SaveUrlFiletoLocal(imageUrl, path) != 0) {
					return;
				}
				Drawable drawable = loadImageFromLocal(path, filename);
				Message message = handler.obtainMessage(0, drawable);
				handler.sendMessage(message);
			}
		}.start();
		
		return null;
	}
	
	private Drawable loadDrawableFromLocal(final String imageUrl) {
		String filename = CommonUrlRequest.getFileNameFromUrl(imageUrl);
		String path = "images/";
		return loadImageFromLocal(path, filename);
	}
	
	public static Drawable loadImageFromLocal(String path, String filename) {
		String imageFile = CommonFileTools.getLocalPath(path) + "/" + filename;
		File file =  new File(imageFile);
		if(file.exists()) {
			return Drawable.createFromPath(imageFile);
		} else {
			return null;
		}
	}

	public interface ImageCallback {
		public void imageLoaded(Drawable imageDrawable, String imageUrl);
	}

}